<template>
	<gui-page ref="guiPage" :customHeader="true">
		<!-- 导航 -->
		<template v-slot:gHeader>
			<nav-bar-custom left-icon="left" :title="$t('Common.IOTScanning')"
				@clickLeftBack="clickLeftBack"></nav-bar-custom>
		</template>

		<template v-slot:gBody>
			<view class="barcodeSplitting">
				<!-- 扫描条码部分 -->
				<view class="gui-bg-white gui-dark-bg-level-3 gui-padding-x distributed-head">
					<view class="custom-card-title">
						<text class="title-line"></text>
						{{ $t('Common.scanningInfo') }}
					</view>
					<view class="custom-card-itemTwo" style="padding: 20rpx 0;">
						<text class="item-info-title"><text class="required-color">*</text>{{
							$t('Common.pointPosition')
						}}：</text>
						<comboGrid requestUrl="/mes/iotBaseinfoH/getIotBaseinfoDPageSet" v-model="data.pointPosition"
							:requestParam="data.inventoryParam" inputKey="code"
							:placeholder="$t('distributedEnter.placeholderTextChoose')"
							:gridPlaceholder="$t('Common.pointPositionCallde')" :column="data.columnPointPosition.column"
							bindValue="code" @setClick="getPointPositionClick">
						</comboGrid>
					</view>
					<view class="gui-form-item gui-border-b" style="padding: 20rpx 0;">
						<text class="item-info-title" style="padding-right: 40rpx;">
							<text class="required-color">*</text>
							{{ $t('Common.barCode') }}
						</text>
						<uni-easyinput class="uni-mt-5" suffixIcon="scan" v-model="data.barCode" type="search"
							:placeholder="$t('Common.scanningBarCode')" @confirm="confirm" @iconClick="iconClick">
						</uni-easyinput>
					</view>
				</view>

				<!-- 提示信息 -->
				<view class="gui-flex gui-rows gui-nowrap gui-align-items-center gui-margin-top">
					<view class="gui-title-line"></view>
					<text class="gui-primary-text gui-h6" style="padding-left:50rpx; padding-right:50rpx;">{{
						$t('hardwareOut.barcodeInformation') }}</text>
					<view class="gui-title-line"></view>
				</view>

				<!-- 条码展示部分 -->
				<scroll-view :show-scrollbar="false" :scroll-y="true" class="scroll">
					<view style="height: 15rpx"></view>
					<view class="card-boxCustom" v-if="data.cardShow">
						<view class="card-body">
							<view class="custom-card-title">
								<text class="title-line"></text>
								{{ $t('distributedOut.atPresent') }}
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{ $t('distributedEnter.barcode')
								}}：</text>{{ data.scanInfo.barCode }}
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{ $t('Common.pointPositionName') }}：</text>
								{{ data.scanInfo.code }}
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{ $t('Common.pointPositionCode') }}：</text>
								{{ data.scanInfo.remark }}
							</view>
						</view>
					</view>
				</scroll-view>

				<!-- 底部确定按钮 -->
				<view class="page-bottom-box bottom-postion">
					<view class="page-bottomBtn bottomBtn-bgcolor-green" @click="submit">{{ $t('calendar.submit') }}</view>
				</view>


				<!-- 弹框填写数量 -->
				<uni-popup ref="inputDialog" type="center">
					<view class="input-dialog-box">
						<view class="input-dialog-content">
							<view class="input-dialog-item">
								{{ $t('distributedEnter.barcode')}}：{{ data.scanInfo.barCode }}
							</view>
							<view class="input-dialog-item">
								{{ $t('Common.pointPositionName') }}:{{ data.scanInfo.code }}
							</view>
							<view class="input-dialog-item" style="font-size: 18px;font-weight: 600;color: red; padding:20rpx 40rpx">{{$t('slottedAsh.confirmWhether') }}</view>
						</view>
						<view class="input-dialog-footer">
							<view class="input-dialog-button" @click="cancelFn">
								{{ $t('popup.cancel') }}
							</view>
							<view class="input-dialog-button dialog-button-left" @click="confirmFn">
								{{ $t('popup.confirm') }}
							</view>
						</view>
					</view>
				</uni-popup>
			</view>
		</template>
	</gui-page>
</template>

<script setup>
//引入文件
import { ref, reactive, onMounted, computed, watch, toRaw } from "vue";
import { barcodeInfoForFeeding, updateD } from '@/api/api.js'
import pdaScan from '@/hooks/pdaScan.js'
import comboGrid from "@/components/comboGrid";
import { onBackPress } from '@dcloudio/uni-app';
import { useStore } from "vuex";
import { basPdaOperationLogFn } from '@/utils/index.js';
import { OPERATION_COMMIT, OPERATION_SCAN } from '@/constant/index.js'
import { DEFAULT_WAREHOUSECODE, DEFAULT_WAREHOUSENAME, DEFAULT_WAREHOUSEID, BIGBARCODER_PRINT } from '@/constant/index.js'
import { onShow } from '@dcloudio/uni-app';

//JS国际化引入
import { useI18n } from 'vue-i18n';
//注册组件
components: { comboGrid }

const { t } = useI18n();

let store = useStore();
const { scan } = pdaScan();

//页面弹框输入数量使用的变量
let inputDialog = ref(null);

const data = reactive({
	pointPosition: '', // 点位
	pointName: '',
	barCode: '',  // 条码
	columnPointPosition: { //点位的下拉里面显示字段
		column: [{
			label: t('Common.pointPositionName'), // 点位名称
			name: "remark",
		}, {
			label: t('Common.pointPositionCode'), // 点位编码
			name: "code",
		}]
	},
	scanInfo: {}, //当前扫描数组
	inventoryParam: {
		typeCode: 'BarcodeScannerConfig',
		warehouseCode: uni.getStorageSync(DEFAULT_WAREHOUSECODE) || '',
		code: ''
	},
	cardShow: false,
	id: null
})

onShow(async () => {
	getRequestData()
	//refresh()
})
//
onMounted(() => {
	uni.$on('scancodedate', (data) => {
		console.log('获取到的code：' + data.code)
		getCode(data.code, 'pda')
	})
})

//仓库设置默认值
const getRequestData = () => {
	console.log(uni.getStorageSync(DEFAULT_WAREHOUSECODE))
	if (uni.getStorageSync(DEFAULT_WAREHOUSECODE) == '') {
		alertDialogOpen()
		return
	} else {
		data.warehouseCode = uni.getStorageSync(DEFAULT_WAREHOUSECODE) || '';
		data.warehouseName = uni.getStorageSync(DEFAULT_WAREHOUSENAME) || '';
		data.locationWarehouseId = uni.getStorageSync(DEFAULT_WAREHOUSEID) || '';
		data.inventoryParam.warehouseCode = uni.getStorageSync(DEFAULT_WAREHOUSECODE) || '';
	}
	// console.log(data.warehouseCode,data.warehouseName,data.locationWarehouseId)
}

const alertDialogOpen = () => {
	uni.showModal({
		content: t('pageTranslation.noDefaultLocation'),
		showCancel: false,
		title: t('smashRemoval.warmPrompt'),
		confirmText: t('pageTranslation.toSet'),
		success: function (res) {
			if (res.confirm) {
				uni.navigateTo({
					url: '/pages/setting/warehouse'
				})
			} else if (res.cancel) {

			}
		}
	});

}

// 点位选事件
const getPointPositionClick = (x) => {
	console.log(x)
	data.pointPosition = x.code
	data.pointName = x.remark
	data.scanInfo = x
	data.id = x.id
}

// 扫描条码事件
const confirm = () => {
	getCode(data.barCode, 'keydown')
}

// 监听用户使用相机
const iconClick = async (type) => {
	if (type === 'suffix') {
		let code = await scan();
		getCode(code, 'scan')
	}
}

const getCode = (code, type) => {
	// 存储扫描的的条码,通过barode去判断是否有重复
	let arr = data.scanList.filter(x => x.barcode == code);
	if (arr.length > 0) {
		uni.showToast({ title: t('smashRemoval.codesRepeatedly'), icon: 'none' });
		return
	}
	try {
		let inputParameter = '无'
		let returnParameter = JSON.stringify(data.scanList)
		let operationPicture = 'IOT扫描'
		let callInterface = '无'
		let opertionParmes = {
			inputParameter,
			returnParameter,
			operationPicture,
			callInterface,
			responseCode: '无', //返回状态
			errorMessage: '无', //错误信息
			isPass: 'Y', //是否成功 Y N
			operationType: OPERATION_SCAN
		}
		basPdaOperationLogFn(opertionParmes)
	} catch (error) {
		console.log(error)
	}
	data.barCode = code
	// 调用扫描的接口
	if (code.length > 0) {
		data.cardShow = true
		data.scanInfo.barCode = code
		data.scanInfo.code = data.pointPosition
		data.scanInfo.remark = data.pointName
		data.scanInfo.value = data.barCode
		data.scanInfo.id = data.id
	}
}

data.scanList = computed(() => {
	console.log(store.state.iotScanning, 'data.scanList')
	return store.state.iotScanning
})

// 提交事件
const submit = () => {
	if (data.pointPosition == "") {
		uni.showToast({ title: t('distributedEnter.placeholderTextChoose'), icon: "none" });
		return
	}
	if (data.barCode == "") {
		uni.showToast({ title: t('stockManage.pleaseScanCode'), icon: "none" });
		return
	}
	//打开弹框
	inputDialog.value.open();
}

const confirmFn = () => {
	// 添加加载框
	uni.showLoading({
		title: 'loading',
		mask: true
	});
	updateD({
		code: data.scanInfo.code,
		value: data.scanInfo.value,
		text: data.scanInfo.text,
		sequence: data.scanInfo.sequence,
		typeCode: data.scanInfo.typeCode,
		remark: data.scanInfo.remark,
		hid: Number(data.scanInfo.id),
	}).then(res => {
		try {
			let inputParameter = JSON.stringify(data.scanInfo)
			let returnParameter = JSON.stringify(res)
			let operationPicture = 'IOT扫描提交'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.status,//返回状态
				errorMessage: res.message,//错误信息
				isPass: res.statusCode == 200 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_COMMIT
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		if (res.statusCode == 200) {
			//隐藏加载框
			uni.hideLoading();
			data.scanInfo = {}
			data.barCode = ''
			uni.showToast({ title: res.message });
			inputDialog.value.close();

		} else {
			uni.hideLoading();
			//uni.showToast({ title: res.message });
			uni.showModal({
				content: res.message,
				showCancel:false
			})
		}
	})
}

//点击物理按键的返回
onBackPress((options) => {
	if (options.from == 'backbutton') {
		if (!data.scanwoodenList.length) {
			uni.navigateBack({
				delta: 1
			});
			return true
		}
		uni.showModal({
			title: t('smashRemoval.warmPrompt'),
			content: t('materials.unsubmittedDataIn'),
			success: function (res) {
				if (res.confirm) {
					//清除store 里面的数据
					store.commit("clearIotScanningList");
					uni.navigateBack({
						delta: 1
					});
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
		return true;
	}
})

//导航栏左侧返回
const clickLeftBack = () => {
	navBackCheck()
}
const navBackCheck = () => {
	if (!data.barcodeList.length) {
		uni.navigateBack({
			delta: 1
		});
		return true
	}
	uni.showModal({
		title: t('smashRemoval.warmPrompt'),
		content: t('materials.unsubmittedDataIn'),
		success: function (res) {
			if (res.confirm) {
				store.commit('clearIotScanningList') // 清空条码数据
				uni.navigateBack({
					delta: 1
				});
			} else if (res.cancel) {
				console.log('用户点击取消');
			}
		}
	});
}
const refresh = () => {
	uni.redirectTo({
		url: '/pages/IOTScanning/IOTScanning'
	});
}

// 弹框的取消按钮
const cancelFn = () => {
	inputDialog.value.close();
}
</script>

<style lang="scss" scoped>
.barcodeSplitting {
	display: flex;
	flex-direction: column;
	height: calc(100vh - 88rpx);
	// height: 100vh;
}

.distributed-head {
	border-bottom-left-radius: 16rpx;
	border-bottom-right-radius: 16rpx;
}

.scroll {
	flex: 1;
	height: 2rpx;
}
</style>
